<template>
  <div ref="chartContainer" style="width: 100%; height: 100%"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import * as echarts from 'echarts'
import { GeoJson } from '@/assets/geoJson'
echarts.registerMap('china', GeoJson)

const props = defineProps({
  options: {
    type: Object,
    required: true,
  },
})

const chartContainer = ref(null)
let chartInstance = null

// 监听窗口变化的回调
const resizeChart = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

// 初始化图表
const initChart = () => {
  const container = chartContainer.value
  if (container) {
    chartInstance = echarts.init(container)
    chartInstance.setOption(props.options)
    window.addEventListener('resize', resizeChart)
  }
}

// 监听 props.options 变化
watch(
  () => props.options,
  (newOptions) => {
    if (chartInstance) {
      chartInstance.setOption(newOptions)
    }
  },
  { deep: true },
)

// 销毁图表
onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  window.removeEventListener('resize', resizeChart)
})

// 组件挂载时初始化
onMounted(() => {
  initChart()
})
</script>
